import {
  List,
  Image,
  ActionSheet,
  PullToRefresh,
  InfiniteScroll,
  NavBar,
  Toast,
  Switch,
} from "antd-mobile";
import PieChart from "../../../component/echarts";
import styles from "./index.module.css";
import { DownOutline } from "antd-mobile-icons";
import youxiu from "../../../image/youxiu.png";
import liangh from "../../../image/linaghao.png";
import jige from "../../../image/jige.png";
import bujige from "../../../image/bujige.png";
import padd from "../../../image/padding.png";
import { useEffect, useRef, useState } from "react";
import CheckPouops from "../../../component/pouop";
import request from "../../../axios";
import { useNavigate, useSearchParams } from "react-router-dom";
import Detail from "../../../component/detail";

interface itemProps {
  [key: string]: string | number;
}

interface statisticProps {
  totalCount: number;
  failCount: number;
  passCount: number;
  goodCount: number;
  excellentCount: number;
  waitCount: number;
  date: string;
  aiTotalRecognitionCount?: number;       // AI总识别数
  aiTodayUnrecognizedCount?: number;      // AI今日未识别
  aiRecognizedEvaluatedCount?: number;    // AI识别菜品已评估
  aiRecognizedWaitCount?: number;         // AI识别菜品待评估
  aiRecognizedFailCount?: number;         // AI识别菜品不及格
  aiRecognizedPassCount?: number;         // AI识别菜品及格
  aiRecognizedGoodCount?: number;         // AI识别菜品良好
  aiRecognizedExcellentCount?: number;    // AI识别菜品优秀
}

interface searchProps {
  shop: itemProps;
  cook: itemProps;
  status: itemProps;
  statu: itemProps;
}

const HisDetail = () => {
  const navigate = useNavigate();
  const [searParams] = useSearchParams();

  // 数字格式化函数 - 添加千分位分隔符
  const formatNumber = (num: number) => {
    return num.toLocaleString();
  };

  // 获取AI评分的优先值：优先使用 aiScorePrediction，fallback到 aiEvaluate
  const getAiScore = (item: any) => {
    return item?.aiScorePrediction !== undefined && item?.aiScorePrediction !== null 
      ? item.aiScorePrediction 
      : item?.aiEvaluate;
  };

  // 获取菜品名称的优先值：优先使用 actualDishName，fallback到 actualAiPredictedDishName
  const getDishName = (item: any) => {
    return item?.actualDishName || item?.actualAiPredictedDishName;
  };

  // 判断是否有有效的菜品名称
  const hasValidDishName = (item: any) => {
    return !!(item?.actualDishName || item?.actualAiPredictedDishName);
  };

  // 判断是否应该显示AI评价：有菜品名称 且 AI评分不为0（待评估）
  const shouldShowAiEvaluation = (item: any) => {
    const hasName = hasValidDishName(item);
    const aiScore = getAiScore(item);
    return hasName && aiScore > 0;
  };
  const handler = useRef<any>(null);
  const handler1 = useRef<any>(null);
  const [hasMore, setHasMore] = useState(true);
  const [nowInfo, setNowInfo] = useState<any>({});
  const [titleObj, setTitle] = useState<statisticProps>({
    totalCount: 0,
    failCount: 0,
    passCount: 0,
    goodCount: 0,
    excellentCount: 0,
    waitCount: 0,
    date: "",
    aiTotalRecognitionCount: 0,
    aiTodayUnrecognizedCount: 0,
    aiRecognizedEvaluatedCount: 0,
    aiRecognizedWaitCount: 0,
    aiRecognizedFailCount: 0,
    aiRecognizedPassCount: 0,
    aiRecognizedGoodCount: 0,
    aiRecognizedExcellentCount: 0,
  });
  const [dataList, setDataList] = useState<any[]>([]);

  const [pageNo, setPageNo] = useState<number>(1);
  const pageSize = 10;
  const [shopList, setShop] = useState<any[]>([]);

  const [cookList, setCook] = useState<any[]>([]);

  const [visible, setVisible] = useState<boolean>(false);
  const [visible1, setVisible1] = useState<boolean>(false);
  const [visible2, setVisible2] = useState<boolean>(false);

  const [searchObj, setSearchObj] = useState<searchProps>({
    shop: {
      name: "门店名称",
      value: "",
    },
    cook: {
      name: "菜谱名称",
      value: "",
    },
    status: {
      name: "AI评价",
      value: "",
    },
    statu: {
      name: "人工评价",
      value: "",
    },
  });
  
  const [includeBlurry, setIncludeBlurry] = useState(false); // 是否包含模糊图片

  const actions: any[] = [
    {
      text: "全部",
      key: "all",
      onClick: () => {
        setSearchObj({
          ...searchObj,
          status: {
            name: "AI评价",
            value: "",
          },
        });
        handler.current?.close();
      },
    },
    {
      text: "已识别",
      key: "group",
      disabled: true,
      style: {
        color: "#999",
        fontSize: "16px",
        backgroundColor: "transparent",
        textAlign: "center",
        padding: "12px 0",
      },
    },
    {
      text: "　　优秀",
      key: "open",
      onClick: () => {
        setSearchObj({
          ...searchObj,
          status: {
            name: "优秀",
            value: "4",
          },
        });
        handler.current?.close();
      },
    },
    {
      text: "　　良好",
      key: "close",
      onClick: () => {
        setSearchObj({
          ...searchObj,
          status: {
            name: "良好",
            value: "3",
          },
        });
        handler.current?.close();
      },
    },
    {
      text: "　　及格",
      key: "close",
      onClick: () => {
        setSearchObj({
          ...searchObj,
          status: {
            name: "及格",
            value: "2",
          },
        });
        handler.current?.close();
      },
    },
    {
      text: "　　不及格",
      key: "close",
      onClick: () => {
        setSearchObj({
          ...searchObj,
          status: {
            name: "不及格",
            value: "1",
          },
        });
        handler.current?.close();
      },
    },
    {
      text: "待识别",
      key: "close",
      onClick: () => {
        setSearchObj({
          ...searchObj,
          status: {
            name: "待识别",
            value: "0",
          },
        });
        handler.current?.close();
      },
    },
  ];

  const actions1: any[] = [
    {
      text: "全部",
      key: "all",
      onClick: () => {
        setSearchObj({
          ...searchObj,
          statu: {
            name: "人工评价",
            value: "",
          },
        });
        handler1.current?.close();
      },
    },
    {
      text: "优秀",
      key: "open",
      onClick: () => {
        setSearchObj({
          ...searchObj,
          statu: {
            name: "优秀",
            value: "4",
          },
        });
        handler1.current?.close();
      },
    },
    {
      text: "良好",
      key: "close",
      onClick: () => {
        setSearchObj({
          ...searchObj,
          statu: {
            name: "良好",
            value: "3",
          },
        });
        handler1.current?.close();
      },
    },
    {
      text: "及格",
      key: "close",
      onClick: () => {
        setSearchObj({
          ...searchObj,
          statu: {
            name: "及格",
            value: "2",
          },
        });
        handler1.current?.close();
      },
    },
    {
      text: "不及格",
      key: "close",
      onClick: () => {
        setSearchObj({
          ...searchObj,
          statu: {
            name: "不及格",
            value: "1",
          },
        });
        handler1.current?.close();
      },
    },
    {
      text: "待评估",
      key: "close",
      onClick: () => {
        setSearchObj({
          ...searchObj,
          statu: {
            name: "待评估",
            value: "0",
          },
        });
        handler1.current?.close();
      },
    },
  ];

  const handleSearch = (type: string) => {
    if (type === "shop") {
      setVisible(true);
    } else if (type === "cook") {
      setVisible1(true);
    } else if (type === "status") {
      handler.current = ActionSheet.show({
        actions: actions,
        cancelText: "取消",
        className: "ai-evaluation-sheet",
        onClose: () => {
          // Toast.show("动作面板关闭");
        },
      });
    } else if (type === "statu") {
      handler1.current = ActionSheet.show({
        actions: actions1,
        cancelText: "取消",
        onClose: () => {
          // Toast.show("动作面板关闭");
        },
      });
    }
  };

  useEffect(() => {
    // 提取通用逻辑为函数
    const getCheckedItem = (list: any) =>
      Array.isArray(list) ? list.filter((item) => item.checked)[0] : null;

    // 获取选中的门店和菜谱
    const selectedShop = getCheckedItem(shopList);
    const selectedCook = getCheckedItem(cookList);

    // 合并状态更新，减少渲染次数
    setSearchObj((prev) => ({
      ...prev,
      shop: selectedShop
        ? { name: selectedShop.name, value: selectedShop.id }
        : { name: "门店名称", value: "" },
      cook: selectedCook
        ? { name: selectedCook.name, value: selectedCook.id }
        : { name: "菜谱名称", value: "" },
    }));
  }, [shopList, cookList]);

  // 获取头部信息
  const getTitle = async () => {
    const objData = JSON.parse(searParams.get("obj") || "{}");
    setTitle({
      totalCount: objData?.totalCount || 0,
      failCount: objData?.failCount || 0,
      passCount: objData?.passCount || 0,
      goodCount: objData?.goodCount || 0,
      excellentCount: objData?.excellentCount || 0,
      waitCount: objData?.waitCount || 0,
      date: objData?.date || "",
      aiTotalRecognitionCount: objData?.aiTotalRecognitionCount || 0,
      aiTodayUnrecognizedCount: objData?.aiTodayUnrecognizedCount || 0,
      aiRecognizedEvaluatedCount: objData?.aiRecognizedEvaluatedCount || 0,
      aiRecognizedWaitCount: objData?.aiRecognizedWaitCount || 0,
      aiRecognizedFailCount: objData?.aiRecognizedFailCount || 0,
      aiRecognizedPassCount: objData?.aiRecognizedPassCount || 0,
      aiRecognizedGoodCount: objData?.aiRecognizedGoodCount || 0,
      aiRecognizedExcellentCount: objData?.aiRecognizedExcellentCount || 0,
    });
  };

  // 获取列表数据
  const getDataList = async (page: number = 1, append: boolean = false) => {
    try {
      const params: any = {
        date: searParams.get("date"),
        pageNo: page,
        pageSize,
        storeId: searchObj?.shop?.value || null,
        dishName: searchObj?.cook?.value ? searchObj?.cook?.name : null,
        aiStatus: searchObj?.status?.value || null,
        personStatus: searchObj?.statu?.value || null,
      };
      
      // 默认排除模糊图片（只显示清晰图片），当用户勾选包含模糊图片时才不传此参数
      if (!includeBlurry) {
        params.fuzzyScore = 43;
      }
      
      const { data } = await request.get("/meal_record/list", params);

      if (page === 1) {
        setDataList(data?.records || []);
      } else {
        setDataList((prev) => [...prev, ...(data?.records || [])]);
      }

      // 更新是否有更多数据
      setHasMore(
        data?.records?.length >= pageSize &&
          (data?.total || 0) > page * pageSize
      );
    } catch (error) {
      console.error("获取数据失败:", error);
    }
  };

  const getShopList = async () => {
    const { data } = await request.get("/store/list", {
      pageNo: 1,
      pageSize: 999,
    });
    if (data) {
      setShop(data?.records || []);
    }
  };

  const getCookList = async () => {
    const { data } = await request.get("/dish/list", {
        pageNo: 1,
        pageSize: 999,
      });
    if (data) {
      setCook(data?.records || []);
    }
  };

  // 加载更多数据
  const loadMore = async () => {
    await getDataList(pageNo + 1, true);
    setPageNo((prev) => prev + 1);
  };

  const handleClick = (item: any, index: number) => {
    if (
      JSON.parse(localStorage.getItem("info") || "{}")?.permission.includes("0")
    ) {
      // 跳转到菜品查看器页面，传递菜品列表和当前索引
      const dishListParam = encodeURIComponent(JSON.stringify(dataList));
      navigate(`/dish/viewer?dishList=${dishListParam}&index=${index}`);
    } else {
      Toast.show("暂无权限");
    }
  };

  const handleChange = async (val: any) => {
    try {
      await request.post("/meal_record/score", {
        ...val,
        personEvaluate: val.personEvaluate[0],
      });
      getDataList(1);
      setPageNo(1);
    } catch (error) {}
  };

  // 搜索条件变化时重置分页
  useEffect(() => {
    setPageNo(1);
    getDataList(1);
  }, [searchObj, includeBlurry]);

  // 初始化加载数据
  useEffect(() => {
    getTitle();
    getDataList(1);
    getShopList();
    getCookList();
  }, []);

  const typeEnum: any = {
    "0": "待评估",
    "1": "不及格",
    "2": "及格",
    "3": "良好",
    "4": "优秀",
  };

  const aiTypeEnum: any = {
    "0": "待识别",
    "1": "不及格",
    "2": "及格",
    "3": "良好",
    "4": "优秀",
  };

  return (
    <div className={styles.tab}>
      <NavBar
        onBack={() => {
          navigate(-1);
        }}
        className={styles.top}
      >
                {searParams.get("date")}     {" "}
      </NavBar>
      <div className={styles.center}>
        <PieChart 
          totalCount={titleObj.totalCount}
          excellentCount={titleObj.aiRecognizedExcellentCount || 0}
          goodCount={titleObj.aiRecognizedGoodCount || 0}
          passCount={titleObj.aiRecognizedPassCount || 0}
          failCount={titleObj.aiRecognizedFailCount || 0}
          waitCount={titleObj.aiTodayUnrecognizedCount || 0}
        />
      </div>
      <div className={styles.aiStats}>
        <div className={styles.aiStatsCard}>
          <div className={styles.aiStatsItem}>
            <div className={styles.aiIndicator}></div>
            <span className={styles.aiStatsLabel}>AI识别菜品已评估</span>
            <span className={styles.aiStatsValue}>
              {formatNumber(titleObj.aiRecognizedEvaluatedCount || 0)}份
            </span>
          </div>
          <div className={styles.aiStatsItem}>
            <div className={styles.aiIndicatorTotal}></div>
            <span className={styles.aiStatsLabel}>AI总识别数</span>
            <span className={styles.aiStatsValue}>
              {formatNumber(titleObj.aiTotalRecognitionCount || 0)}份
            </span>
          </div>
        </div>
      </div>
      <div className={styles.bottom}>
        <div className={styles.title}>
          {new Array(4).fill("").map((item, index) => {
            const type =
              index === 0
                ? "shop"
                : index === 1
                ? "cook"
                : index === 2
                ? "status"
                : "statu";

            return (
              <span className={styles.title_span} key={index}>
                <span onClick={() => handleSearch(type)}>
                  {searchObj?.[`${type}`].name}
                </span>
                <DownOutline fontSize={12} style={{ marginLeft: "5px" }} />
              </span>
            );
          })}
        </div>
        <div className={styles.filterRow}>
          <div className={styles.blurryFilter}>
            <span className={styles.blurryLabel}>包含模糊图片</span>
            <Switch
              checked={includeBlurry}
              onChange={(checked) => setIncludeBlurry(checked)}
            />
          </div>
        </div>
        <div className={styles.content}>
          <PullToRefresh
            onRefresh={async () => {
              await getDataList(1);
              return Promise.resolve();
            }}
          >
            {dataList?.map((item: any, index: number) => {
              const aiScore = getAiScore(item);
              const shouldShowAI = shouldShowAiEvaluation(item);
              
              // 如果显示AI评价，使用AI评分；否则使用人工评价
              const displayScore = shouldShowAI ? aiScore : item?.personEvaluate;
              
              const url =
                displayScore === 4
                  ? youxiu
                  : displayScore === 3
                  ? liangh
                  : displayScore === 2
                  ? jige
                  : displayScore === 1
                  ? bujige
                  : padd;
              const styName =
                displayScore === 4
                  ? "bingo"
                  : displayScore === 3 || displayScore === 2
                  ? "good"
                  : displayScore === 1
                  ? "fail"
                  : "padd";

              const styName1 =
                item?.personEvaluate === 4
                  ? "bingo"
                  : item?.personEvaluate === 3 || item?.personEvaluate === 2
                  ? "good"
                  : item?.personEvaluate === 1
                  ? "fail"
                  : "padd";

              return (
                <List.Item className={styles.content_item} key={index}>
                  <div
                    className={styles.items}
                    onClick={() => handleClick(item, index)}
                  >
                    <div className={styles.item_left}>
                      <Image
                        src={item?.dishPicture || ""}
                        width={88}
                        height={64}
                        fit="cover"
                        style={{ borderRadius: "8px 8px" }}
                      />
                    </div>
                    <div className={styles.item_center}>
                      <div className={styles.center_one}>
                        {getDishName(item) || "菜品名称待完善"}
                      </div>
                      <div className={styles.center_two}>
                        {item?.tags?.length ? (
                          item?.tags
                            ?.split("#")
                            .filter((item: any) => item !== "")
                            .map((tag: string, idx: number) => (
                              <span key={idx}>{tag}</span>
                            ))
                        ) : (
                          <span>暂无标签</span>
                        )}
                      </div>
                      <div className={styles.center_three}>
                        {item?.storeName || "-"}
                      </div>
                      <div className={styles.center_three}>
                        {item?.recordTime || "-"}
                      </div>
                    </div>
                    <div className={styles.item_right}>
                      {shouldShowAiEvaluation(item) && (
                        <span className={styles?.[styName]}>
                          AI: {aiTypeEnum[aiScore] || "待识别"}
                        </span>
                      )}
                      <span className={styles?.[styName1]}>
                        人工: {typeEnum[item?.personEvaluate] || "待评估"}
                      </span>
                      <Image
                        src={url}
                        width={70}
                        height={styName === "padd" ? 68 : 63}
                        style={{ marginTop: "10px" }}
                      />
                    </div>
                  </div>
                </List.Item>
              );
            })}
            <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
          </PullToRefresh>
        </div>
      </div>
      <CheckPouops
        data={shopList}
        setData={setShop}
        value={visible}
        setValue={setVisible}
        type="radio"
      />
      <CheckPouops
        data={cookList}
        setData={setCook}
        value={visible1}
        setValue={setVisible1}
        type="radio"
      />
      <Detail
        value={visible2}
        cook={cookList}
        setValue={setVisible2}
        obj={nowInfo}
        callback={(val: any) => {
          handleChange(val);
        }}
      />
    </div>
  );
};

export default HisDetail;
